<template>
  <div class="com">
    <!-- <span class="fs-xxs c-primary" @tap.stop="isShowPanel = true">录制声音</span> -->
    <button v-if="isAuthorizeRecord == 'N'" class="ta-c ui btn empty" open-type="openSetting">
      <span style="height: 36px;width: 36px;"><i class="if icon-audio" style="font-size: 23px;"></i></span>
      <div class="fs-xt" style="padding-top: 2px;">语音</div>
    </button>
    <div v-else @tap.stop="onStartRecord" class="ta-c">
      <span style="height: 34px;width: 36px;"><i class="if icon-audio" style="font-size: 25px;position: relative;top: -2px;"></i></span>
      <div class="fs-xt">语音</div>
    </div>
    <div v-if="isShowPanel" class="panel ripple fadeIn" @tap="onOther">
      <div class="panel-bd ripple slideInUp" style="padding-bottom: 20px;padding-top: 12px;" @tap.stop="onPanelHdTap">
        <div class="pdb-s" :class="{'c-gray': status != 'recording'}">
          <div class="fs-1 tip-time ta-c" style="font-weight: 500;" :class="{'c-primary': status == 'recording', 'recording': status == 'recording'}">{{recordTimeTip}}</div>
        </div>
        <div class="handle">
          <div v-if="status == 'unrecord'" class="handle-inner" @tap.stop="status = 'recording'">
            录音
          </div>
          <div v-if="status == 'recording'" class="handle-inner" @tap.stop="status = 'record-done'">
            结束
          </div>
          <div v-if="status == 'record-done'" class="handle-inner">
            结束
          </div>
        </div>
        <div class="close" @tap.stop="status = 'record-cancel'"><i class="if icon-close"></i></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState, mapGetters } from 'vuex'
import * as _wechat from '@/utils/wechat'
const MAX_DURATION = 580000
const RECORD_MANAGER = wx.getRecorderManager()

export default {
  props: {},
  data() {
    return {
      isShowPanel: false,
      status: 'unrecord',
      tempFilePath: '',
      recordSeconds: 0,
      fileSize: 0,
      duration: 0,
      isAuthorizeRecord: ''
    }
  },
  async mounted () {
    let setting = await _wechat.getSetting()
    if (typeof setting['scope.record'] !== 'undefined' && setting['scope.record']) {
      this.isAuthorizeRecord = 'Y'
    } else if (typeof setting['scope.record'] !== 'undefined' && !setting['scope.record']) {
      this.isAuthorizeRecord = 'N'
    }
  },
  computed: {
    recordTimeTip() {
      let lf = Math.round(this.recordSeconds)
      let s = lf % 60
      let m = Math.round(lf / 60)
      if (s < 10) s = '0' + s
      if (m < 10) m = '0' + m
      return `${m}:${s}`
    }
  },
  methods: {
    ...mapActions([
      'setEx',
      'setIsModel'
    ]),
    onUploadBack () {
      wx.hideLoading()
    },
    reset () {
      this.status = 'unrecord'
      this.tempFilePath = ''
      this.recordSeconds = 0
      this.fileSize = 0
      this.duration = 0
    },
    onStartRecord () {
      let that = this
      wx.authorize({
        scope: 'scope.record',
        success () {
          that.isAuthorizeRecord = 'Y'
          that.isShowPanel = true
        },
        fail (msg) {
          that.isAuthorizeRecord = 'N'
        }
      })
    },
    onOther () {
      this.$store.commit('UI_SET_TOAST_WARNING_MSG', '请先暂停录音')
    },
    onPanelHdTap () {}
  },
  watch: {
    recordSeconds(nv) {
      if (nv >= MAX_DURATION / 1000) {
        this.status = 'record-done'
      }
    },
    isShowPanel (nv) {
      if (!nv) {
        this.$emit('close')
        return
      }
      this.$emit('open')
      this.reset()
      this.status = 'recording'
    },
    async status(nv) {
      this.$emit('status-change', nv)
      if (this.it) clearInterval(this.it)
      if (nv === 'recording') {
        this.setEx('___')
        this.setIsModel(true)
        this.$emit('start')
        this.$emit('started', {type: 'audio'})
        this.recordSeconds = 0
        this.it = setInterval(() => {
          this.recordSeconds++
        }, 1000)
        RECORD_MANAGER.start({
          duration: MAX_DURATION,
          sampleRate: 44100,
          numberOfChannels: 1,
          encodeBitRate: 192000,
          format: 'aac',
          frameSize: 50
        })
        RECORD_MANAGER.onStop(res => {
          if (this.status === 'record-cancel') return
          let {tempFilePath, fileSize, duration} = res
          this.tempFilePath = tempFilePath
          this.fileSize = fileSize
          this.duration = duration
          this.$emit('success', {type: 'audio', path: tempFilePath, size: fileSize, duration})
        })
      } else if (nv === 'record-done') {
        this.setIsModel(false)
        RECORD_MANAGER.stop()
        this.isShowPanel = false
      } else if (nv === 'record-cancel') {
        this.setIsModel(false)
        RECORD_MANAGER.stop()
        this.isShowPanel = false
      }
    }
  }
}
</script>

<style scoped lang="less">
@import '../assets/less/var.less';
.panel {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
  box-sizing: border-box;
  &-bd {
    box-shadow: 0px -1px 3px rgba(0, 0, 0, 0.065);
    z-index: 1001;
    background-color: white;
    position: absolute;
    bottom: 0;
    width: 100%;
    text-align: center;
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
  }
}
.handle {
  width: 96px;
  height: 96px;
  background-color: lighten(@colorPrimary, 50%);
  color: @colorWhite;
  margin: 0 auto;
  border-radius: 50%;
  font-size: 1.8 * @baseSize;
  position: relative;
  box-sizing: border-box;
  &-inner {
    box-sizing: border-box;
    line-height: 80px;
    display: block;
    position: absolute;
    left: 8px;
    top: 8px;
    width: 80px;
    height: 80px;
    background-color: @colorSecondary;
    border-radius: 50%;
    z-index: 0;
    &:active {
      background-color: darken(@colorSecondary, 10%);
    }
  }
}
i {
  font-size: 2.4 * @baseSize;
}
.close {
  position: absolute;
  right: 8px;
  top: 0px;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  line-height: 40px;
  z-index: 1001;
  i {
    font-size: 12px;
    color: #ccc;
  }
}
.tip-time {
  display: inline-block;
  position: relative;
  &.recording::after {
    position: absolute;
    content: "";
    display: block;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background-color: #FF4C4C;
    left: -10px;
    top: 50%;
    margin-top: -3px;
  }
}
span {
  position: relative;
  top: 9px;
}
</style>
